<?php
/**
 * 国内发货需求文件,审查
 * User: bgl
 * Date: 2022/11/3
 * Time: 16:51
 */

namespace App\Admin\Controllers\Delivery;

use App\Admin\Actions\File\Delivery\ImportReviewFile;
use App\Admin\Ajax\Delivery\DeliveryReviewAjax;
use App\Exporter\Delivery\DeliveryViewExporter;
use App\Models\Basics\SysPlat;
use App\Models\Delivery\DeliveryReview;
use App\Util\User;
use Encore\Admin\Admin as SAdmin;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Form;
use Encore\Admin\Grid;
use Encore\Admin\Controllers\AdminController;
use Illuminate\Http\Request as FRequest;
class DeliveryReviewController extends AdminController{

    protected $title = 'CN-发货需求确认';

    protected function grid()
    {
        SAdmin::script($this->_script());
        $grid = new Grid(new DeliveryReview());
        $grid->model()->orderBy('id', 'DESC');
        $grid->model()->orderBy('status', 'ASC');
        $grid->column('id', 'ID');
        $grid->column('plat_id','平台')->using(SysPlat::options()->toArray());
        $grid->column('type','类型')->using(DeliveryReview::$_type);
        $grid->column('file_name','需求文件')->view('delivery.delivery-review.file');
        $grid->column('tag_name', '标签文件')->view('delivery.delivery-review.tag');
        $grid->column('is_fnsku','是否标贴');
        $grid->column('seller_id','销售')->display(function ($value){
            return User::getUsernameById($value);
        });
        $grid->column('status','状态')->using(DeliveryReview::$_status);
        $grid->column('created_at','创建时间')->sortable();
        $grid->column('操作')->view('delivery.delivery-review.action');
        $grid->disableActions();
        $grid->disableCreateButton();
        $grid->exporter(new DeliveryViewExporter());

        if(Admin::user()->can('fba.upload')){
            $grid->tools(function (Grid\Tools $tools) {
                $tools->append(new ImportReviewFile());
            });
        }

        $grid->filter(function($filter){
            $filter->column(1/3, function ($filter) {
                $filter->equal('seller_id','销售')->select(User::getSellerOptions());
                $filter->between('created_at','日期')->datetime();
            });
            $filter->column(1/3, function ($filter) {
                $filter->equal('plat_id','平台')->select(SysPlat::options());
                $filter->in('is_fnsku','标贴')->checkbox(DeliveryReview::$_isFnsku);
            });
            $filter->column(1/3, function ($filter) {
                $filter->in('status','状态')->checkbox(DeliveryReview::$_status);
                $filter->in('type','类型')->checkbox(DeliveryReview::$_type);
            });
        });
        return $grid;
    }

    protected function _script()
    {
        $token = csrf_token();
        return <<<EOT

//删除需求文件及数据
$('.grid-row-delete').unbind('click').click(function() {
    var id = $(this).data('id');
    swal({
        title: "确认删除?",
        type: "warning",
        showCancelButton: true,
        confirmButtonColor: "#DD6B55",
        confirmButtonText: "确认",
        showLoaderOnConfirm: true,
        cancelButtonText: "取消",
        preConfirm: function() {
            return new Promise(function(resolve) {
                $.ajax({
                    method: 'post',
                    url: '/xqc/delivery/review/' + id,
                    data: {
                        _method:'delete',
                        _token: "{$token}",
                    },
                    success: function (data) {
                        resolve(data);
                    }
                });
            });
        }
    }).then(function(result) {
        var data = result.value;
        if (typeof data === 'object') {
            if (data.status) {
                $.pjax.reload('#pjax-container');
                toastr.success('删除成功 !');
            } else {
                swal(data.message, '', 'error');
            }
        }
    });
});

//删除标签，并修改tag_status=1，tag_name=null
$('.grid-row-delete-tag').unbind('click').click(function() {
    var id = $(this).data('id');
    swal({
        title: "确认删除?",
        type: "warning",
        showCancelButton: true,
        confirmButtonColor: "#DD6B55",
        confirmButtonText: "确认",
        showLoaderOnConfirm: true,
        cancelButtonText: "取消",
        preConfirm: function() {
            return new Promise(function(resolve) {
                $.ajax({
                    method: 'post',
                    url: '/xqc/delivery/review-ajax',
                    data: {
                        action:'deleteTag',
                        param:id,
                        _token: "{$token}",
                    },
                    success: function (data) {
                        resolve(data);
                    }
                });
            });
        }
    }).then(function(result) {
        var data = result.value;
        if (typeof data === 'object') {
            if (data.status) {
                $.pjax.reload('#pjax-container');
                toastr.success('删除成功 !');
            } else {
                swal(data.message, '', 'error');
            }
        }
    });
});

//上传标签
$('.grid-upload-tag').on('click', function () {
    var id = $(this).data('id');
    $.ajax({
        method: 'post',
        url: '/xqc/delivery/review-ajax',
        data: {
            action:'checkModal',
            param:id,
            _token: "{$token}",
        },
        success: function (data) {
            if (typeof data === 'object') {
                if (data.status) {
                    $("#myModal").modal({
                        remote : '/xqc/delivery/review-modal?action=tagFile&param=' + id
                    });
                } else {
                    swal(data.message, '', 'error');
                }
            }
        }
    });
});
$("#myModal").on("hidden.bs.modal", function() {
    $(this).removeData("bs.modal");
    $(this).find(".modal-content").children().remove();
});

//确认
$('.grid-row-ajax').unbind('click').click(function(e) {
    e.preventDefault();
    var id = $(this).data('id');
    var action = $(this).data('action');
    $.ajax({
        method: 'post',
        url: '/xqc/delivery/review-ajax',
        data: {
            _token: "{$token}",
            param:id,
            action:action
        },
        success: function (data) {
            if (typeof data === 'object') {
                if (data.status) {
                    $.pjax.reload('#pjax-container');
                    toastr.success('提交成功 !');
                } else {
                    swal(data.message, '', 'error');
                }
            }
        }
    });
});
EOT;
    }

    public function ajax(){
        $action = request('action');
        $param = request('param');
        $ajax = new DeliveryReviewAjax();
        return $param ? call_user_func([$ajax,$action],$param) : call_user_func([$ajax,$action]);
    }

    public function trace(FRequest $request){
        $action = $request->get('action');
        $param = $request->get('param');
        $file = $request->file('source_file');
        $trace = new DeliveryReviewAjax();
        return $param ? call_user_func([$trace,$action],$file,$param) : call_user_func([$trace,$action],$file);
    }

    public function modal(){
        $action = request('action');
        $param = request('param');
        $modal = new DeliveryReviewAjax();
        return $param ? call_user_func([$modal,$action],$param) : call_user_func([$modal,$action]);
    }

    protected function download()
    {
        $id = request('id');
        $fileFlag = request('file');
        $f = DeliveryReview::query()->find($id);
        if(!$f) {
            admin_toastr('无文件记录！','error');
            return back();
        }
        try{
            $fileDir = DeliveryReview::fileDir($f->type,strtotime($f->created_at));
            $file = public_uploads_path($fileDir).DIRECTORY_SEPARATOR.$f->{$fileFlag};
            if(!file_exists($file)){
                admin_toastr('无文件！','error');
                return back();
            }
            return response()->download($file);
        }catch (\Exception $e){
            report($e);
            admin_toastr('操作失败！','error');
            return back();
        }
    }

    public function form()
    {
        return new Form(new DeliveryReview());
    }

}
